package com.ruoyi.system.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义元数据对象处理器，实现自动填充功能
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    /**
     * 新增操作自动填充
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        // 获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            // 填充创建人ID和姓名
            this.strictInsertFill(metaObject, "creatorId", Long.class, loginUser.getUserId());
            this.strictInsertFill(metaObject, "creatorName", String.class, loginUser.getUsername());
        }
        // 填充创建时间
        this.strictInsertFill(metaObject, "createdTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updatedTime", LocalDateTime.class, LocalDateTime.now());
    }

    /**
     * 更新操作自动填充
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        // 获取当前登录用户信息
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser != null) {
            // 填充修改人ID和姓名
            this.strictUpdateFill(metaObject, "updaterId", Long.class, loginUser.getUserId());
            this.strictUpdateFill(metaObject, "updaterName", String.class, loginUser.getUsername());
        }
        // 填充更新时间
        this.strictUpdateFill(metaObject, "updatedTime", LocalDateTime.class, LocalDateTime.now());
    }
}
